package com.suoyue.store.controller;

import com.suoyue.store.service.ex.PasswordErrorException;
import com.suoyue.store.service.ex.ServiceException;
import com.suoyue.store.service.ex.UserNotFoundException;
import com.suoyue.store.service.ex.UsernameDuplicatedException;
import com.suoyue.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;
import java.util.Date;

/** 控制器类的基类 */
public class BaseController {
    /** 操作成功的状态码 */
    public static final int OK = 200;

    /** @ExceptionHandler用于统一处理方法抛出的异常 */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicatedException) {
            result.setState(400);
        } else if (e instanceof ServiceException) {
            result.setState(500);
        }else if (e instanceof UserNotFoundException) {
            result.setState(4001);
        } else if (e instanceof PasswordErrorException) {
            result.setState(4002);
        }
        return result;
    }

    protected final Integer getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    protected final String getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }

}
